package com.whsxt.service.impl;

import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whsxt.constant.AuthConstant;
import com.whsxt.domain.SysUser;
import com.whsxt.mapper.SysUserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserMapper sysUserMapper;
    /*
    * 登录方法
    * 前台用户和后台用户是公用一个登录方法的，所以为了区分是哪一个用户
    * 我们需要在header里面做一个标识，指明是前台用户还是后台用户
    * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取 request
        ServletRequestAttributes requestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=requestAttributes.getRequest();
        //获取头信息
        String loginType=request.getHeader(AuthConstant.LOGIN_TYPE);
        if(StringUtils.isEmpty(loginType)){
            return null;
        }
        //选择:查询哪一个表格
        switch(loginType){
            case AuthConstant.SYS_USER:
                //后台用户，就查看后台用户的 sysUser 表
                SysUser sysUser=sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername,username)
                );
                //如果查询到的用户不为空
                if(!ObjectUtils.isEmpty(sysUser)){
                    //查询权限
                    List<String> auths=sysUserMapper.findUserAuthsById(sysUser.getUserId());
                    if(!CollectionUtils.isEmpty(auths)){
                        //设置权限
                        sysUser.setAuths(auths);
                    }
                }
                return sysUser;
            case AuthConstant.MEMBER:
                    //查前台用户的表格
                    return null;
            default:
                return null;
        }
    }
}
